<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/12
 * Time: 19:33

 * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com

 */
namespace app\admin\controller;
use app\common\model\AmountLog;
use app\common\model\MessageTemplate;
use app\common\model\UserCommission;
use app\common\model\UserGzh;
use app\common\model\UserXcx;
use app\services\wechat\Miniprogram;
use app\services\wechat\Offiaccount;
use think\Request;
class Withdrawal
{
    public function withdrawalList(Request $request)
    {
        $param = $request->param();
        $withdrawalModel = new \app\common\model\Withdrawal();
        $where = [];
        if (isset($param['pay_mode']) && !empty($param['pay_mode'])) {
            $where['pay_mode'] = $param['pay_mode'];
        }
        if (isset($param['name']) && !empty($param['name'])) {
            $userWhere[] = ['phone|nickname', 'like', '%' . $param['name'] . '%'];
            $userModel = new \app\common\model\User();
            $userArray = $userModel->where($userWhere)->select()->toArray();
            if ($userArray){
                $where[] = ['uid','in',array_column($userArray,'id')];
            }else{
                return   success('提现列表', ['list' => [], 'count' => 0]);
            }
        }
        if (isset($param['start_time']) && !empty($param['start_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['end_time']) && !empty($param['end_time'])) {
            $where[] = ['create_time', '>=', strtotime($param['start_time'])];
        }
        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['status', '=', strtotime($param['status'])];
        }
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $list = $withdrawalModel->where($where)->limit($start, $limit)->order('create_time','desc')->select()->toArray();
        if ($list) {
            $uidArray = array_column($list, 'uid');
            $userModel = new \app\common\model\User();
            $userList = $userModel->where('id', 'in', $uidArray)
                ->field('id,phone,nickname,avatar')
                ->select()->toArray();
            $userListById = array_column($userList, null, 'id');
            foreach ($list as $key => $value) {
                $list[$key]['phone'] = $userListById[$value['uid']]['phone'];
                $list[$key]['nickname'] = $userListById[$value['uid']]['nickname'];

                $list[$key]['avatar'] = $userListById[$value['uid']]['avatar'];
            }
        }
        $count = $withdrawalModel->where($where)->count();
        return success('提现列表', ['list' => $list, 'count' => $count]);
    }
    public function withdrawalReject(Request $request)
    {
        $param = $request->param();
        $withdrawalModel = new \app\common\model\Withdrawal();
        $withdrawalInfo = $withdrawalModel->where(['id' => $param['id']])->find();
        if ($withdrawalInfo['status'] != 1) {
            return error('订单状态有误');
        }
        $userModel = new \app\common\model\User();
        try {
            $withdrawalModel->startTrans();
            $withdrawalModel->where(['id' => $param['id']])->update(['status' => 4, 'remark' => $param['remark']]);
            $userModel->where(['id' => $withdrawalInfo['uid']])->inc('surplus_income', $withdrawalInfo['number'])->update();
            $withdrawalModel->commit();
        } catch (\Exception $exception) {
            $withdrawalModel->rollback();
            return error($exception->getMessage());
        }
        return success('操作成功');

    }
    public function withdrawalPass(Request $request)
    {
        $param = $request->param();
        $withdrawalModel = new \app\common\model\Withdrawal();
        $withdrawalInfo = $withdrawalModel->where(['id' => $param['id']])->find();
       // $withdrawalInfo->where(['id' => $param['id']])->update(['status' => 2]);
        if ($withdrawalInfo['status'] != 1) {
            $withdrawalInfo->where(['id' =>$param['id'] ])->update(['status' => $withdrawalInfo['status']]);
            return error('订单状态有误');
        }
        $userModel = new \app\common\model\User() ;
        $userInfo = $userModel->where(['id' => $withdrawalInfo['uid']])->find();
        if ($withdrawalInfo['pay_mode'] == 1) {
            $offiaccount = new Offiaccount();

            $userGzhModel = new UserGzh() ;
            $userGzhInfo = $userGzhModel->where(['id' =>$userInfo['user_gzh_id'] ])->find();
            $returnRequest = $offiaccount->withdrawal($userGzhInfo['openid'], $withdrawalInfo);
            if (isset($returnRequest['code'])  && $returnRequest['code'] == 'NOT_ENOUGH' ){
                $withdrawalModel->where(['id' =>$param['id'] ])->update(['status' => 1]);
                return error('微信提示：'.$returnRequest['message']);
            }
            if (isset($returnRequest['code'])  && $returnRequest['code'] == 'PARAM_ERROR' ){
                $withdrawalModel->where(['id' =>$param['id'] ])->update(['status' => 1]);
                return error('微信提示：'.$returnRequest['message']);
            }
            if (isset($returnRequest['batch_status']) && $returnRequest['batch_status'] != 'ACCEPTED'|| $returnRequest['batch_status'] != 'PROCESSING' ||$returnRequest['batch_status'] != 'FINISHED'){
                $withdrawalModel->where(['id' =>$param['id'] ])->update(['status' => 1]);
                return error('微信提示：'.$returnRequest['message']);
            }
        }elseif ($withdrawalInfo['pay_mode'] == 3){
            $Miniprogram= new Miniprogram();
            $userGzhModel = new UserXcx() ;
            $userGzhInfo = $userGzhModel->where(['id' =>$userInfo['user_xcx_id'] ])->find();

            $returnRequest = $Miniprogram->withdrawal($userGzhInfo['openid'], $withdrawalInfo);
            if (isset($returnRequest['batch_status']) && $returnRequest['batch_status'] != 'ACCEPTED'|| $returnRequest['batch_status'] != 'PROCESSING'||$returnRequest['batch_status'] != 'FINISHED'){
                  $withdrawalModel->where(['id' =>$param['id'] ])->update(['status' => 1]);
                  return error('微信提示：',$returnRequest['message']);
            }
        }
        $withdrawalModel->where(['id' => $param['id']])->update(['status' => 3, 'update_time' => time()]);
        $userModel->where(['id' => $withdrawalInfo['uid']])->inc('withdrawn_amount', $withdrawalInfo['amount'])->update();
     /*   $userCommissionModel = new UserCommission();
        $commissionData = [
            'trigger_uid' => $userInfo['id'],
            'receive_uid' =>$userInfo['id'],
            'level' => 0,
            'amount' => $withdrawalInfo['number'],
            'ratio' => $withdrawalInfo['ratio'],
            'order_id' => $withdrawalInfo['id'],
            'create_time' => time(),
            'type' => 4,
        ];
        if ($commissionData['amount'] > 0){
            $userCommissionModel->insert($commissionData);
        }*/
        $amountModel = new AmountLog();
        $amountData  = [
            'uid' => $request->userInfo['id'],
            'amount' => $withdrawalInfo['number'],
            'amount_type' => 2,
            'amount_direction' => 2,
            'create_time' => time(),
            'correlation_id' => $withdrawalInfo['id'],
            'operation_source' => 5,
            'handling_fees' => $withdrawalInfo['fees']
        ];
        $currency_name  = \app\common\model\Config::getConfigValue('currency_name');
        $amountModel->insert($amountData);
        $messageModel = new MessageTemplate();
        $gzhMessage[0]['data'] = [
            'amount2' => ['value' => $withdrawalInfo['number'].$currency_name],
            'amount5' => ['value' => $withdrawalInfo['amount']],
            'amount4' => ['value' =>$withdrawalInfo['fees'].$currency_name],
            'time5' => ['time3' => date('Y-m-d H:i:s')],
        ];
        $gzhMessage[0]['uid'] =$withdrawalInfo['uid'];
        $gzhMessage[0]['title'] ='withdrawal';
        $messageModel->sendMessage(1,$gzhMessage);

        $messageModel = new MessageTemplate();
        $xcxMessage[0]['data'] = [
            'amount2' => ['value' => $withdrawalInfo['number'].$currency_name],
            'amount16' => ['value' => $withdrawalInfo['amount']],
            'amount7' => ['value' =>$withdrawalInfo['fees'].$currency_name],
            'date4' => ['time3' => date('Y-m-d H:i:s')],
        ];
        $xcxMessage[0]['uid'] =$withdrawalInfo['uid'];
        $xcxMessage[0]['title'] ='withdrawal';
        $messageModel->sendMessage(1,$gzhMessage);

        $messageModel-> sendAliMessage($userInfo['id'], 'withdrawal', ['money' => $withdrawalInfo['amount']]);


        return success('成功');
    }
}